package com.big.auth.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.big.auth.domain.dto.AuthLoginDTO;
import com.big.auth.service.AuthService;
import com.big.common.core.exception.CustomerException;
import com.big.common.core.result.Result;
import com.big.common.core.result.ResultCode;
import com.big.common.saToken.domain.dto.LoginDTO;
import com.big.user.api.domain.dto.SysUserDTO;
import com.big.user.api.feign.RemoteUserFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author 山归岿
 * @create 2025-06-22-02:38
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final RemoteUserFeignClient userFeignClient;


    @Override
    public LoginDTO login(AuthLoginDTO authLoginVO) {
        // 验证码校验（需要实现验证码服务）
        // validateCaptcha(loginDTO.getCaptchaKey(), loginDTO.getCaptcha());

        // 用户名密码校验
        SysUserDTO user = getByUsername(authLoginVO.getUsername());
        if (user == null) {
            throw new CustomerException(ResultCode.USERNAME_PASSWORD_ERROR);
        }

        if (!BCrypt.checkpw(authLoginVO.getPassword(), user.getPassword())) {
            throw new CustomerException(ResultCode.USERNAME_PASSWORD_ERROR);
        }

        if (ObjectUtil.equal(1, user.getStatus())) {
            throw new CustomerException(ResultCode.USER_DISABLED);
        }

        // 执行登录
        // 判断是否记住我
        if (Boolean.TRUE.equals(authLoginVO.getRememberMe())) {
            StpUtil.login(user.getId(), true);
        } else {
            StpUtil.login(user.getId());
        }
        String tokenValue = StpUtil.getTokenValue();

        // 获取用户角色权限信息（需要实现角色权限服务）
        // List<String> permissions = roleService.getUserPermissions(user.getId());

        // 构建登录返回信息
        LoginDTO build = LoginDTO.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .token(tokenValue)
                .tokenType(StpUtil.getTokenName())
                .tokenExpireIn(StpUtil.getTokenTimeout())
                .roleId(user.getRoleId())
                .roleName(user.getRoleName())
                .deptId(user.getDeptId())
                .deptName(user.getDeptName())
                // .permissions(permissions.toArray(new String[0]))
                .build();

        // 同时存储用户信息供UserUtil使用
        StpUtil.getSession().set("userInfo", build);
        return build;
    }

    @Override
    public SysUserDTO getByUsername(String username) {
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setUsername(username);
        Result<SysUserDTO> one = userFeignClient.getOneDTO(sysUserDTO);
        if (!one.isSuccess()) {
            throw new CustomerException(one.getMessage());
        }
        return one.getData();
    }

    @Override
    public SysUserDTO getCurrentUser() {
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setId(StpUtil.getLoginIdAsString());
        Result<SysUserDTO> one = userFeignClient.getOneDTO(sysUserDTO);
        if (!one.isSuccess()) {
            throw new CustomerException(one.getMessage());
        }
        return one.getData();
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        SysUserDTO user = getCurrentUser();
        if (!BCrypt.checkpw(oldPassword, user.getPassword())) {
            throw new CustomerException("原密码错误");
        }
        user.setPassword(BCrypt.hashpw(newPassword));
        this.userFeignClient.updateByIdDTO(user);
    }

    @Override
    public void resetPassword(String userId) {
        if (Objects.equals(StpUtil.getLoginIdAsString(), userId)) {
            throw new CustomerException("不能修改自己的密码");
        }
        Result<SysUserDTO> one = this.userFeignClient.getOneDTO(SysUserDTO.builder().id(userId).build());
        if (!one.isSuccess()) {
            throw new CustomerException(one.getMessage());
        }
        if (ObjectUtil.equal(1, one.getData().getStatus())) {
            throw new CustomerException(ResultCode.USER_DISABLED);
        }
        SysUserDTO user = new SysUserDTO();
        user.setId(userId);
        one = this.userFeignClient.getOneDTO(user);
        if (!one.isSuccess()) {
            throw new CustomerException(one.getMessage());
        }
        // 默认密码可以配置在配置文件中
        user.setPassword(BCrypt.hashpw("123456"));
        this.userFeignClient.updateByIdDTO(user);
    }
}
